{% extends 'base.html' %}
{% load static %}

{% block title %}本地有约 - 发现身边有趣的活动{% endblock %}

{% block extra_css %}
<style>
    .hero-section {
        background: var(--gradient-primary);
        color: white;
        padding: 5rem 0;
        margin-bottom: 3rem;
        position: relative;
        overflow: hidden;
    }
    
    .hero-section::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="rgba(255,255,255,0.1)" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,112C672,96,768,96,864,112C960,128,1056,160,1152,160C1248,160,1344,128,1392,112L1440,96L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>') no-repeat bottom;
        background-size: cover;
    }
    
    .hero-content {
        position: relative;
        z-index: 1;
    }
    
    .search-box {
        background: white;
        border-radius: 3rem;
        padding: 0.5rem;
        box-shadow: var(--shadow-lg);
        max-width: 600px;
        margin: 2rem auto;
    }
    
    .search-box input {
        border: none;
        padding: 0.75rem 1.5rem;
        font-size: 1.1rem;
    }
    
    .search-box input:focus {
        outline: none;
        box-shadow: none;
    }
    
    .search-box button {
        border-radius: 2rem;
        padding: 0.75rem 2rem;
    }
    
    .feature-card {
        text-align: center;
        padding: 2rem;
        background: white;
        border-radius: 1rem;
        box-shadow: var(--shadow-md);
        transition: all 0.3s ease;
        height: 100%;
    }
    
    .feature-card:hover {
        transform: translateY(-10px);
        box-shadow: var(--shadow-lg);
    }
    
    .feature-icon {
        width: 80px;
        height: 80px;
        margin: 0 auto 1.5rem;
        background: var(--gradient-primary);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2rem;
        color: white;
    }
    
    .category-card {
        background: white;
        border-radius: 1rem;
        padding: 1.5rem;
        box-shadow: var(--shadow-md);
        text-align: center;
        transition: all 0.3s ease;
        cursor: pointer;
    }
    
    .category-card:hover {
        transform: translateY(-5px);
        box-shadow: var(--shadow-lg);
        background: var(--gradient-primary);
        color: white;
    }
    
    .category-icon {
        font-size: 2.5rem;
        margin-bottom: 1rem;
    }
    
    .section-title {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 2rem;
        text-align: center;
    }
    
    .section-title::after {
        content: '';
        display: block;
        width: 60px;
        height: 4px;
        background: var(--gradient-primary);
        margin: 1rem auto 0;
        border-radius: 2px;
    }
</style>
{% endblock %}

{% block content %}
<!-- 英雄区 -->
<div class="hero-section">
    <div class="container hero-content">
        <div class="text-center">
            <h1 class="display-3 fw-bold mb-3">发现身边有趣的活动</h1>
            <p class="lead mb-4">结识志同道合的朋友，开启精彩生活</p>
            
            <!-- 搜索框 -->
            <div class="search-box">
                <div class="input-group">
                    <input type="text" 
                           class="form-control" 
                           id="searchInput" 
                           placeholder="搜索感兴趣的活动...">
                    <button class="btn btn-gradient-primary" onclick="searchActivities()">
                        <i class="fas fa-search"></i> 搜索
                    </button>
                </div>
            </div>
            
            <!-- 统计数据 -->
            <div class="row mt-5">
                <div class="col-md-3 col-6 mb-3">
                    <div class="text-center">
                        <h2 class="display-4 fw-bold" id="totalActivities">0</h2>
                        <p class="mb-0">活动总数</p>
                    </div>
                </div>
                <div class="col-md-3 col-6 mb-3">
                    <div class="text-center">
                        <h2 class="display-4 fw-bold" id="totalUsers">0</h2>
                        <p class="mb-0">注册用户</p>
                    </div>
                </div>
                <div class="col-md-3 col-6 mb-3">
                    <div class="text-center">
                        <h2 class="display-4 fw-bold" id="todayActivities">0</h2>
                        <p class="mb-0">今日活动</p>
                    </div>
                </div>
                <div class="col-md-3 col-6 mb-3">
                    <div class="text-center">
                        <h2 class="display-4 fw-bold" id="hotActivities">0</h2>
                        <p class="mb-0">热门活动</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container mb-5">
    <!-- 活动分类 -->
    <section class="mb-5">
        <h2 class="section-title">浏览分类</h2>
        <div class="row g-3" id="categoriesContainer">
            <div class="col-12 text-center">
                <div class="loader"></div>
            </div>
        </div>
    </section>
    
    <!-- 推荐活动 -->
    <section class="mb-5">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2 class="section-title mb-0">
                {% if user.is_authenticated %}
                    <i class="fas fa-magic"></i> 为你推荐
                {% else %}
                    <i class="fas fa-fire"></i> 热门活动
                {% endif %}
            </h2>
            <a href="/activities/" class="btn btn-outline-primary">
                查看更多 <i class="fas fa-arrow-right"></i>
            </a>
        </div>
        <div class="row" id="recommendedActivities">
            <div class="col-12 text-center py-5">
                <div class="loader"></div>
            </div>
        </div>
    </section>
    
    <!-- 即将开始 -->
    <section class="mb-5">
        <h2 class="section-title">即将开始</h2>
        <div class="row" id="upcomingActivities">
            <div class="col-12 text-center py-5">
                <div class="loader"></div>
            </div>
        </div>
    </section>
    
    <!-- 平台特色 -->
    <section class="mb-5">
        <h2 class="section-title">平台特色</h2>
        <div class="row g-4">
            <div class="col-md-3 col-sm-6">
                <div class="feature-card">
                    <div class="feature-icon">
                        <i class="fas fa-search"></i>
                    </div>
                    <h5>智能发现</h5>
                    <p class="text-muted">基于兴趣推荐，精准匹配活动</p>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="feature-card">
                    <div class="feature-icon">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <h5>安全可靠</h5>
                    <p class="text-muted">实名认证，保障活动安全</p>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="feature-card">
                    <div class="feature-icon">
                        <i class="fas fa-coins"></i>
                    </div>
                    <h5>积分奖励</h5>
                    <p class="text-muted">参与活动赚积分，兑换好礼</p>
                </div>
            </div>
            <div class="col-md-3 col-sm-6">
                <div class="feature-card">
                    <div class="feature-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <h5>社交互动</h5>
                    <p class="text-muted">结识朋友，拓展社交圈</p>
                </div>
            </div>
        </div>
    </section>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 加载统计数据
    function loadStatistics() {
        axios.get('/activities/api/statistics/')
            .then(response => {
                const data = response.data;
                animateNumber('totalActivities', data.total_activities || 0);
                animateNumber('totalUsers', data.total_users || 0);
                animateNumber('todayActivities', data.today_activities || 0);
                animateNumber('hotActivities', data.hot_activities || 0);
            })
            .catch(error => {
                console.error('加载统计数据失败:', error);
                // API未实现时使用0
                animateNumber('totalActivities', 0);
                animateNumber('totalUsers', 0);
                animateNumber('todayActivities', 0);
                animateNumber('hotActivities', 0);
            });
    }
    
    // 数字动画
    function animateNumber(elementId, target) {
        const element = document.getElementById(elementId);
        let current = 0;
        const increment = Math.ceil(target / 50);
        const interval = setInterval(() => {
            current += increment;
            if (current >= target) {
                current = target;
                clearInterval(interval);
            }
            element.textContent = current.toLocaleString();
        }, 20);
    }
    
    // 加载活动分类
    function loadCategories() {
        const categoriesContainer = document.getElementById('categoriesContainer');
        
        fetch('/activities/api/activity_types/')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    categoriesContainer.innerHTML = '';
                    
                    // 由于API没有返回每个分类的活动数量，这里暂时使用随机数
                    data.data.results.slice(0, 8).forEach(category => {
                        const categoryItem = document.createElement('div');
                        categoryItem.className = 'col-lg-3 col-md-4 col-sm-6';
                        categoryItem.innerHTML = `
                            <div class="category-card" onclick="viewCategory(${category.id})"></div>
                        `;
                        
                        const cardContent = categoryItem.querySelector('.category-card');
                        cardContent.innerHTML = `
                            <div class="w-16 h-16 rounded-full bg-blue-100 flex items-center justify-center mx-auto mb-3">
                                <i class="fas fa-tag text-blue-500"></i>
                            </div>
                            <div class="text-center">
                                <span class="font-medium">${category.name}</span>
                                <p class="text-sm text-gray-500">${Math.floor(Math.random() * 100) + 30}个活动</p>
                            </div>
                        `;
                        
                        categoriesContainer.appendChild(categoryItem);
                    });
                }
            })
            .catch(error => {
                console.error('加载活动分类失败:', error);
                // 加载失败时显示一些提示或默认内容
                categoriesContainer.innerHTML = '<p class="text-center py-8 text-gray-500">加载分类失败</p>';
            });
    }
    
    // 加载推荐活动
    function loadRecommendedActivities() {
        const recommendedActivitiesContainer = document.getElementById('recommendedActivities');
        
        fetch('/activities/api/list/?sort=popularity&order=desc&page=1&page_size=3')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    recommendedActivitiesContainer.innerHTML = '';
                    
                    data.data.results.forEach(activity => {
                        // 格式化时间
                        const date = new Date(activity.start_time);
                        const formattedDate = `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
                        
                        const activityCard = document.createElement('div');
                        activityCard.className = 'activity-card bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-shadow duration-300';
                        activityCard.innerHTML = `
                            <div class="relative">
                              <img src="${activity.cover_image || '/static/images/default-activity.jpg'}" 
                                   alt="${activity.title}" 
                                   class="w-full h-40 object-cover">
                              <span class="absolute top-2 left-2 bg-blue-500 text-white text-xs px-2 py-1 rounded-full">
                                ${activity.activity_type ? activity.activity_type.name : '其他'}
                              </span>
                            </div>
                            <div class="p-3">
                              <h3 class="font-medium text-lg mb-1 line-clamp-2"><a href="/activities/${activity.id}/">${activity.title}</a></h3>
                              <div class="flex justify-between items-center text-sm text-gray-500">
                                <div class="flex items-center"><i class="fas fa-map-marker-alt mr-1"></i>${activity.location_name}</div>
                                <div>${formattedDate}</div>
                              </div>
                              <div class="mt-2 flex justify-between items-center">
                                <div class="text-xs text-gray-400">${activity.current_participants}/${activity.max_participants}人参与</div>
                                <div class="text-sm font-medium ${activity.is_free ? 'text-green-500' : 'text-orange-500'}">
                                  ${activity.is_free ? '免费' : '¥' + activity.fee}
                                </div>
                              </div>
                            </div>
                        `;
                        
                        recommendedActivitiesContainer.appendChild(activityCard);
                    });
                }
            })
            .catch(error => {
                console.error('加载推荐活动失败:', error);
                // 加载失败时显示一些提示或默认内容
                recommendedActivitiesContainer.innerHTML = '<p class="text-center py-8 text-gray-500">加载活动失败</p>';
            });
    }
    
    // 加载即将开始的活动
    function loadUpcomingActivities() {
        const upcomingActivitiesContainer = document.getElementById('upcomingActivities');
        
        fetch('/activities/api/list/?sort=start_time&order=asc&page=1&page_size=3')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    upcomingActivitiesContainer.innerHTML = '';
                    
                    data.data.results.forEach(activity => {
                        // 格式化时间
                        const date = new Date(activity.start_time);
                        const formattedDate = `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
                        
                        const activityCard = document.createElement('div');
                        activityCard.className = 'flex items-center space-x-3 p-3 border-b border-gray-100 last:border-0';
                        activityCard.innerHTML = `
                          <div class="w-16 h-16 rounded-lg overflow-hidden flex-shrink-0">
                            <img src="${activity.cover_image || '/static/images/default-activity.jpg'}" 
                                 alt="${activity.title}" 
                                 class="w-full h-full object-cover">
                          </div>
                          <div class="flex-grow min-w-0">
                            <h3 class="font-medium line-clamp-1"><a href="/activities/${activity.id}/">${activity.title}</a></h3>
                            <div class="text-xs text-gray-500 mt-1 flex justify-between">
                              <span>${activity.location_name}</span>
                              <span>${formattedDate}</span>
                            </div>
                          </div>
                        `;
                        
                        upcomingActivitiesContainer.appendChild(activityCard);
                    });
                }
            })
            .catch(error => {
                console.error('加载即将开始的活动失败:', error);
                // 加载失败时显示一些提示或默认内容
                upcomingActivitiesContainer.innerHTML = '<p class="text-center py-8 text-gray-500">加载活动失败</p>';
            });
    }
    
    // 渲染活动列表
    function renderActivities(containerId, activities) {
        const container = document.getElementById(containerId);
        
        if (activities.length === 0) {
            container.innerHTML = `
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-calendar-times"></i>
                        <h3>暂无活动</h3>
                    </div>
                </div>
            `;
            return;
        }
        
        container.innerHTML = activities.map(activity => `
            <div class="col-lg-3 col-md-6 mb-4">
                <div class="activity-card">
                    <div class="activity-image">
                        <img src="${activity.cover_image || '/static/img/default-activity.jpg'}" alt="${activity.title}">
                        <span class="activity-badge">${activity.activity_type?.name || '其他'}</span>
                    </div>
                    <div class="activity-body">
                        <h5 class="activity-title">
                            <a href="/activities/${activity.id}/" class="text-decoration-none text-dark">
                                ${activity.title}
                            </a>
                        </h5>
                        <div class="activity-info">
                            <div class="activity-info-item">
                                <i class="fas fa-calendar"></i>
                                <span>${formatDate(activity.start_time)}</span>
                            </div>
                            <div class="activity-info-item">
                                <i class="fas fa-map-marker-alt"></i>
                                <span>${activity.location_name}</span>
                            </div>
                            <div class="activity-info-item">
                                <i class="fas fa-users"></i>
                                <span>${activity.current_participants}/${activity.max_participants}</span>
                            </div>
                        </div>
                        <div class="activity-footer">
                            <div>
                                <i class="fas fa-eye text-muted"></i> ${formatNumber(activity.view_count)}
                            </div>
                            ${activity.is_free ? 
                                '<span class="badge bg-success">免费</span>' : 
                                `<span class="badge bg-warning">¥${activity.fee}</span>`
                            }
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    // 查看分类
    function viewCategory(typeId) {
        window.location.href = `/activities/?type=${typeId}`;
    }
    
    // 搜索活动
    function searchActivities() {
        const keyword = document.getElementById('searchInput').value.trim();
        window.location.href = `/activities/?search=${encodeURIComponent(keyword)}`;
    }
    
    // 搜索框回车事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchActivities();
        }
    });
    
    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function() {
        loadStatistics();
        loadCategories();
        loadRecommendedActivities();
        loadUpcomingActivities();
    });
</script>
{% endblock %}
